package cn.jlearn.proxy.common.handler;

import cn.jlearn.proxy.common.packet.BsPacket;
import cn.jlearn.proxy.common.body.BaseBody;
import com.alibaba.fastjson.JSON;
import org.tio.core.ChannelContext;

import java.nio.charset.StandardCharsets;

/**
 * @author qianyingchao
 * @version 1.0
 * @date 2021/5/8 5:50 下午
 */
public abstract class AbstractBsHandler<T extends BaseBody> implements BsHandlerInterface {

    /**
     * 返回具体内容包class
     *
     * @return class
     */
    public abstract Class<T> bodyClass();

    @Override
    public void handler(BsPacket packet, ChannelContext channelContext) throws Exception {
        String jsonStr;
        T bsBody = null;
        if (packet.getBody() != null) {
            jsonStr = new String(packet.getBody(), StandardCharsets.UTF_8);
            bsBody = JSON.parseObject(jsonStr, bodyClass());
        }
        handler(packet, bsBody, channelContext);
    }

    /**
     * 具体处理内容包
     *
     * @param packet         业务包
     * @param bsBody         具体内容包
     * @param channelContext 通道
     * @throws Exception 异常
     */
    public abstract void handler(BsPacket packet, T bsBody, ChannelContext channelContext) throws Exception;

}
